package fantasy;

import java.io.IOException;
import java.net.URL;
import java.util.Set;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthException;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.client.spreadsheet.FeedURLFactory;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.spreadsheet.Column;
import com.google.gdata.data.spreadsheet.Data;
import com.google.gdata.data.spreadsheet.Field;
import com.google.gdata.data.spreadsheet.Header;
import com.google.gdata.data.spreadsheet.RecordEntry;
import com.google.gdata.data.spreadsheet.TableEntry;
import com.google.gdata.data.spreadsheet.TableFeed;
import com.google.gdata.data.spreadsheet.Worksheet;
import com.google.gdata.util.ServiceException;

public class GDocPrepSpreadsheetServlet extends HttpServlet {
	
	private SpreadsheetService client = new SpreadsheetService("dhpollack-dhpollack944-v6");
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        PersistenceManager pm = PMF.get().getPersistenceManager();

		GOAuth g = new GOAuth();
		try {
			log("Getting Google Access Tokens for " + user.getNickname());
			Key k = new KeyFactory.Builder(GOAuth.class.getSimpleName(), user.getNickname()).getKey();
			g = pm.getObjectById(GOAuth.class, k);

			String ACCESS_TOKEN = g.getAccessToken();
			String TOKEN_SECRET = g.getAccessTokenSecret();

			GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
			oauthParameters.setOAuthConsumerKey("dhpollack944.appspot.com");
			oauthParameters.setOAuthConsumerSecret("5sLdLvnBuYa+fpcWdzie9ndr");
			oauthParameters.setOAuthToken(ACCESS_TOKEN);
			oauthParameters.setOAuthTokenSecret(TOKEN_SECRET);

			client.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());

		} catch (JDOObjectNotFoundException e) {
			log("User hasn't done the OAuth dance");
			return;
		} catch (OAuthException e) {
			// TODO Auto-generated catch block
			log("OAuthException: " + e.toString());
			e.printStackTrace();
			return;
		}

		String league = req.getParameter("league");
		
		
		GoogleLeagueDoc gdoc = new GoogleLeagueDoc();
		try {
			Key key = KeyFactory.createKey(GoogleLeagueDoc.class.getSimpleName(), league);
			gdoc = (GoogleLeagueDoc) pm.getObjectById(GoogleLeagueDoc.class, key);
		} catch (JDOObjectNotFoundException e) {
			log("GoogleLeagueDoc Not Found");
			log("Key: " + league);
			return;
		}
		
		Set<Key> stats;
		LeagueSettings l = new LeagueSettings();
		try {
			l = pm.getObjectById(LeagueSettings.class, league);
			stats = l.getStats();
		} catch (JDOObjectNotFoundException e) {
			log("LeagueSettings Not Found");
			return;
		}

		FeedURLFactory factory = new FeedURLFactory("https://spreadsheets.google.com");

		
		/* Create Table in Sheet1 */
		/*
		try {
			TableEntry tableEntry = new TableEntry();

			URL tableFeedUrl = factory.getTableFeedUrl(gdoc.getDocResourceId());
			
			//URL tableFeedUrlManual = new URL("https://spreadsheets.google.com/feeds/" + gdoc.getDocResourceId() + "/tables/");
			
			log(tableFeedUrl.toString());

			// Specify a basic table:
			tableEntry.setTitle(new PlainTextConstruct("New Table"));
			tableEntry.setWorksheet(new Worksheet("Sheet1"));
			tableEntry.setHeader(new Header(1));

			// Specify columns in the table, start row, number of rows.
			Data tableData = new Data();
			tableData.setNumberOfRows(0);
			// Start row index cannot overlap with header row.
			tableData.setStartIndex(2);
			// This table has only one column.
			if(stats.iterator().hasNext()) {
				char letter = 'A';
				for(Key s : stats) {
					try {
						StatCategory sc = pm.getObjectById(StatCategory.class, s);
						String uppercase_letter = String.valueOf(letter);
						log(uppercase_letter.toUpperCase() + ": " + sc.getStatDisplayName());
						tableData.addColumn(new Column(uppercase_letter.toUpperCase(), sc.getStatDisplayName()));
						letter++;
					} catch(JDOObjectNotFoundException e) {
						log("Stat Not Found");
						return;
					}
				}
			} else {
				log("Stats was empty");
			}


			tableEntry.setData(tableData);
			client.insert(tableFeedUrl, tableEntry);
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			log("Problem Setting Up Table");
			e.printStackTrace();
		}
		*/
		
		
		try {
			URL tableFeedUrl = factory.getTableFeedUrl(gdoc.getDocResourceId());
			
			
			log("Getting TableFeed");
			TableFeed feed = client.getFeed(tableFeedUrl, TableFeed.class);
			
			for (TableEntry table : feed.getEntries()) {
				String currTitle = table.getTitle().getPlainText();
				log("Table Title: " + currTitle);
				if (currTitle.equals("New Table")) {
					int tableid_slash = table.getId().lastIndexOf("/");
					String tableid = table.getId().substring(tableid_slash+1);
					URL recordsFeedUrl = factory.getRecordFeedUrl(gdoc.getDocResourceId(), tableid);
					log(tableid);
					log("URL: " + recordsFeedUrl.toString());
					RecordEntry newRecord = new RecordEntry();
					if(stats.iterator().hasNext()) {
						for(Key s : stats) {
							try {
								StatCategory sc = pm.getObjectById(StatCategory.class, s);
								newRecord.addField(new Field(null, sc.getStatDisplayName(), sc.getStatName()));
							} catch(JDOObjectNotFoundException e) {
								log("Stat Not Found");
								return;
							}
						}
					}
					RecordEntry insertedRecord = client.insert(recordsFeedUrl, newRecord);
					log("Inserted Record: " + insertedRecord.getId());
				}
			}

		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			log("Spreadsheet ServiceException");
			e.printStackTrace();
		}
		
		log("Finished!");

		
	}


}
